package com.by.hellosecurityoauth2.config;

import com.by.hellosecurityoauth2.domain.TAuthority;
import com.by.hellosecurityoauth2.domain.TUser;
import com.by.hellosecurityoauth2.domain.TUserRole;
import com.by.hellosecurityoauth2.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名获取用户，并验证用户是否有效及权限
        //询用户数据库进行比对
        TUser user = userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        boolean enabled = user.getStatus() == 1; // 可用性 :true:可用 false:不可用
        boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
        boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
        boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定
        //配置权限
//        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("test:test:create");
//        grantedAuthorities.add(grantedAuthority);
        List<TAuthority> authorities = userService.getUserAuthorities(user);
        if (authorities != null && authorities.size() > 0) {
            for (TAuthority authority :
                    authorities) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getAuthorityCode());
                grantedAuthorities.add(grantedAuthority);
            }
        }

        //将用户名和密码及其他配置返还个spring security 进行验证
        return new User(username, user.getPassword(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
    }

}
